package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.data.ESPageUtil;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.service.ElasticsearchService;
import com.dongdongshop.service.GoodsService;
import com.dongdongshop.util.PageUtil;
import com.google.gson.JsonObject;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@org.springframework.stereotype.Service
public class EsServiceImpl implements ElasticsearchService {

    @Autowired
    private JestClient jestClient;

    @Autowired
    private SearchSourceBuilder searchSourceBuilder;

    @Reference
    private GoodsService goodsService;

    @Override
    public void insertElasticsearch(Long[] ids) throws IOException {
        for (Long id : ids) {
            TbGoods goods = goodsService.getGoodsById(id);
            Index index = new Index.Builder(goods).index("dongdongshop").type("goods").id(goods.getId().toString()).build();

            //执行
            jestClient.execute(index);
            System.out.println("执行成功");
        }
    }

    @Override
    public PageUtil listSearchByName(Integer pageNum, Integer pageSize, String searchName) throws IOException {
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(searchName, "goodsName", "caption");
        searchSourceBuilder.query(multiMatchQueryBuilder);

        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //设置高亮前缀
        highlightBuilder.preTags("<span style='color:red' >");
        //设置高亮字段
        highlightBuilder.field("goodsName");
        highlightBuilder.field("caption");
        //设置高亮后缀
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        return getSearch(pageNum,pageSize,searchName);
    }

    public PageUtil getSearch(Integer pageNum, Integer pageSize, String searchName) throws IOException {
        //设置起始位置
        searchSourceBuilder.from((pageNum - 1) * pageSize);
        searchSourceBuilder.size(pageSize);//每页大小
//        searchSourceBuilder.sort("price", SortOrder.DESC);
        String queryJson = searchSourceBuilder.toString();
        //创建搜索对象
        Search search = new Search.Builder(queryJson).addIndex("dongdongshop").build();
        SearchResult result = null;
        result = jestClient.execute(search);
        List<SearchResult.Hit<TbGoods, Void>> hits = result.getHits(TbGoods.class);
        List<TbGoods> goodsList = new ArrayList<>();
        //java8新特性循环遍历list
        hits.stream().forEach(x -> {
            //高亮替换
            TbGoods goods = x.source;
            Map<String, List<String>> highlight = x.highlight;
            if (null != highlight) {
                List<String> nameList = highlight.get("goodsName");
                List<String> captionList = highlight.get("caption");
                if (null != nameList){
                    if (goods.getGoodsName().contains(searchName)){
                        goods.setGoodsName(nameList.get(0));
                    }
                }
                if (null != captionList){
                    if (goods.getCaption().contains(searchName)){
                        goods.setCaption(captionList.get(0));
                    }
                }
                goodsList.add(goods);
            }
           // System.out.println(goods);
        });
        JsonObject jsonObject = result.getJsonObject();
        Long total = ESPageUtil.getTotal(jsonObject);
        return new PageUtil(pageNum,pageSize,total,goodsList);
    }
}
